package com.example.day03_32.base;

import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.example.day03_32.util.ToastUtil;
import com.example.day03_32.widget.LoadingDialog;

import butterknife.ButterKnife;
import butterknife.Unbinder;

public abstract class BaseLazyFragment<P extends BasePresenter> extends Fragment implements BaseView {
    private View mView;
    private Unbinder unbinder;
    protected P mPresenter;
    private boolean mDataLoaded;
    private boolean mIsViewCreated;
    private boolean mIsVisibleToUser;
    private LoadingDialog mLoadingDialog;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {

        if (mView == null) {
            mView = inflater.inflate(getLayout(), null);
            unbinder = ButterKnife.bind(this, mView);
            mPresenter = initPresenter();
            if (mPresenter != null) {
                mPresenter.bindView(this);
            }
            initView(mView);
            mIsViewCreated = true;
            lazyLoad();
            initListener();
        }

        return super.onCreateView(inflater, container, savedInstanceState);
    }

    protected abstract void initListener();

    private void lazyLoad() {
        if (mIsViewCreated && mIsVisibleToUser&& !mDataLoaded){
            mDataLoaded=true;
            initData();
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        this.mIsVisibleToUser=isVisibleToUser;
        lazyLoad();
    }

    protected abstract void initData();

    protected abstract void initView(View mView);

    protected abstract P initPresenter();

    protected abstract int getLayout();

    @Override
    public void onDestroy() {
        super.onDestroy();
        unbinder.unbind();
        if(mPresenter!=null){
            mPresenter.destroy();
            mPresenter=null;
        }
        hideLoading();
    }

    @Override
    public void showToast(String msg) {
        ToastUtil.showToastShort(msg);
    }


    @Override
    public void showLoading() {
        if (mLoadingDialog == null) {
            mLoadingDialog = new LoadingDialog(getContext());
        }
        mLoadingDialog.show();
    }

    @Override
    public void hideLoading() {
        if (mLoadingDialog != null){
            mLoadingDialog.dismiss();
        }
    }
}
